export default {
  namespaced: true,
  state: {
    car: uni.getStorageSync('carList') || []
  },
  mutations: {
    setCar (state, payload) {
      let item = state.car.find(item => {
        return item.goods_id === payload.goods_id
      })
      if (item) {
        item.good_number++
      } else {
        state.car.push(payload)
      }
      // state.car.forEach(item => {
      //   console.log(item.goods_id === payload.goods_id);
      //   if (item.goods_id === payload.goods_id) {
      //     item.good_number++
      //     uni.setStorageSync('carLst', state.car)
      //   } else {
      //     state.car.push(payload)
      //   }
      // });

      uni.setStorageSync('carList', state.car)
    },
    // 修改商品状态
    updateGoodsStatus (state, payload) {
      // 找到对应的商品id,然后再修改对应商品的状态
      let goods = state.car.find(item => { return item.goods_id === payload.goods_id })
      goods.goods_status = payload.goods_status
      // 修改完之后保存在本地
      uni.setStorageSync('carList', state.car)
    },
    // 修改商品的数量
    updateGoodsNumber (state, payload) {
      let goods = state.car.find(item => { return item.goods_id === payload.goods_id })
      goods.good_number = payload.good_number
    },
    // 删除商品信息
    deleteGoods (state, payload) {
      state.car.forEach((item, index) => {
        if (item.goods_id == payload) {
          state.car.splice(index, 1)
        }
      })
      // 修改完之后保存在本地
      uni.setStorageSync('carList', state.car)
    },
    changeSingleStatus (state, payload) {
      state.car.forEach(item => item.goods_status = payload)
      // 修改完之后保存在本地
      uni.setStorageSync('carList', state.car)

    }
  },
  // 使用getter属性来计算出购物车一共有多少个
  // getters表示vuex中的计算属性，具有缓存作用
  getters: {
    getTotalNumber (state) {
      let total = 0
      state.car.forEach(item => {
        // if (item.goods_status) {
        total += item.good_number
        // }
      })
      return total
    },
    // 获取仓库的所有商品
    getGoods (state) {
      return state.car
    },
    allCheck (state) {
      let res = state.car.every(item => {
        return item.goods_status === true
      })
      return res
    },
    // 获取选中商品的件数
    getTotalSelectGoods (state) {
      let total = 0
      state.car.forEach(item => {
        if (item.goods_status) {
          total += item.good_number
        }
      })
      return total
    },
    // 获取选中商品的总价格
    getTotalSelectGoodsPrice (state) {
      let total = 0
      state.car.forEach(item => {
        if (item.goods_status) {
          total += item.good_number * item.goods_price
        }
      })
      return total.toFixed(2)
    },
  }
}